package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.stark.apkextract.lib.model.AeExportInfo;
import com.stark.apkextract.lib.model.AeExporter;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AppAdapter;
import flc.ast.bean.ApkBean;
import flc.ast.bean.MyDocBean;
import flc.ast.databinding.ActivityExportRecordBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class ExportRecordActivity extends BaseAc<ActivityExportRecordBinding> {

    private AppAdapter appAdapter;
    private boolean isEdit = false;
    private List<ApkBean> listSel = new ArrayList<>();
    private AttachPopupView attachPopupView;
    private boolean isSelectAll = false;
    private Dialog myDeleteDialog;
    private ApkBean selBean;


    @Override
    protected int onCreate() {
        return R.layout.activity_export_record;
    }

    @Override
    protected void initView() {
        mDataBinding.ivExportRecordBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvApkList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        appAdapter = new AppAdapter();
        mDataBinding.rvApkList.setAdapter(appAdapter);
        appAdapter.addChildClickViewIds(R.id.ivAppItemEdit);
        appAdapter.setOnItemChildClickListener(this);
        appAdapter.setOnItemClickListener(this);
        appAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (!isEdit) {
                    isEdit = true;
                    appAdapter.setEdit(isEdit);
                    appAdapter.notifyDataSetChanged();
                    mDataBinding.tvSelNum.setVisibility(View.VISIBLE);
                    mDataBinding.llExportRecordBottom.setVisibility(View.VISIBLE);
                } else {
                    listSel.clear();
                    isEdit = false;
                    appAdapter.setEdit(isEdit);
                    loadApks();
                    mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listSel.size()));
                    mDataBinding.tvSelNum.setVisibility(View.GONE);
                    mDataBinding.llExportRecordBottom.setVisibility(View.GONE);
                }
                return true;
            }
        });
        mDataBinding.llSelectAll.setOnClickListener(this);
        mDataBinding.llDelete.setOnClickListener(this);
        mDataBinding.llShare.setOnClickListener(this);
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llSelectAll://全选
                listSel.clear();
                if (isSelectAll) {
                    for (ApkBean validDatum : appAdapter.getValidData()) {
                        validDatum.setSelected(false);
                    }
                } else {
                    for (ApkBean validDatum : appAdapter.getValidData()) {
                        validDatum.setSelected(true);
                        listSel.add(validDatum);
                    }
                }
                isSelectAll();
                appAdapter.notifyDataSetChanged();
                break;
            case R.id.llDelete://删除
                if (listSel.size() == 0) {
                    return;
                }
                myDeleteDialog.show();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm:
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            case R.id.llShare://分享
                share();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (appAdapter.getItem(position).isSelected()) {
                appAdapter.getItem(position).setSelected(false);
                listSel.remove(appAdapter.getItem(position));
                appAdapter.notifyDataSetChanged();
            } else {
                listSel.add(appAdapter.getItem(position));
                appAdapter.getItem(position).setSelected(true);
                appAdapter.notifyDataSetChanged();
            }
            isSelectAll();
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        ApkBean item = appAdapter.getItem(position);
        switch (view.getId()) {
            case R.id.ivAppItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.delete), getString(R.string.share), getString(R.string.install)},
                                new int[]{R.drawable.ashanchu, R.drawable.afenx, R.drawable.aanzhuang},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                selBean = item;
                                                myDeleteDialog.show();
                                                break;
                                            case 1:
                                                IntentUtil.shareFile(mContext, (AppUtils.getAppPath(item.pkgName)));
                                                break;
                                            case 2:
                                                //安装
                                                startActivity(IntentUtils.getInstallAppIntent(AppUtils.getAppPath(item.pkgName)));
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvSelNum.setVisibility(View.GONE);
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, 0));
        loadApks();
    }

    private void loadApks() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<AeExportInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AeExportInfo>> emitter) {
                emitter.onNext(AeExporter.getInstance().getExportInfos());
            }

            @Override
            public void accept(List<AeExportInfo> packageNames) {
                if (!CollectionUtils.isEmpty(packageNames)) {
                    mDataBinding.rvApkList.setVisibility(View.VISIBLE);
                    mDataBinding.ivExportRecordNoData.setVisibility(View.GONE);
                    List<ApkBean> apkBeans = new ArrayList<>();
                    ApkBean bean;
                    for (AeExportInfo packageName : packageNames) {
                        bean = new ApkBean();
                        bean.pkgName = packageName.packageName;
                        bean.info = packageName;
                        apkBeans.add(bean);
                    }
                    appAdapter.setList(apkBeans);
                } else {
                    mDataBinding.rvApkList.setVisibility(View.GONE);
                    mDataBinding.ivExportRecordNoData.setVisibility(View.VISIBLE);
                }
                dismissDialog(500L);
            }
        });
    }

    private void isSelectAll() {
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listSel.size()));
        if (listSel.size() == appAdapter.getValidData().size()) {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.ayiquanx);
            isSelectAll = true;
        } else {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.aquanx);
            isSelectAll = false;
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        if (listSel.size() != 0) {
                            for (ApkBean apkBean : listSel) {
                                AeExporter.getInstance().delExport(apkBean.info);
                            }
                        } else {
                            AeExporter.getInstance().delExport(selBean.info);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        listSel.clear();
                        isEdit = false;
                        appAdapter.setEdit(isEdit);
                        loadApks();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listSel.size()));
                        mDataBinding.tvSelNum.setVisibility(View.GONE);
                        mDataBinding.llExportRecordBottom.setVisibility(View.GONE);
                    }
                });
            }
        }, 1000);
    }

    private void share() {
        if (listSel.size() == 0) {
            return;
        }
        if (listSel.size() > 1) {
            ToastUtils.showShort(getString(R.string.share_one_app));
            return;
        }
        IntentUtil.shareFile(mContext, (AppUtils.getAppPath(listSel.get(0).pkgName)));
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

}